package com.kensure.shike.qiniu.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import co.kensure.frame.Const;
import co.kensure.frame.JSBaseService;
import co.kensure.mem.Utils;

import com.alibaba.fastjson.JSONObject;
import com.kensure.mycom.config.service.MyConfigService;
import com.kensure.shike.qiniu.model.SKImage;
import com.kensure.shike.weixin.service.WeixinSignService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

/**
 * 微信签名业务
 * 
 * @author fankd created on 2019-2-20
 * @since
 */
@Service
public class QiNiuService extends JSBaseService {

	@Resource
	private WeixinSignService weixinSignService;
	// 要上传的空间
	public static String bucket = "shike";

	// 定义两个成员变量常量
	// 获取临时素材(视频不能使用https协议)
	private static final String GET_TMP_MATERIAL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";

	public SKImage fetchTmpFile(String media_id) {
		String token = weixinSignService.getToken();
		String url = String.format(GET_TMP_MATERIAL, token, media_id);
		return fetchFile(url);
	}

	// 抓取接口
	public SKImage fetchFile(String url) {
		try {
			// 构造一个带指定Zone对象的配置类
			Configuration cfg = new Configuration(Zone.autoZone());
			Auth me = getAuth();
			BucketManager bucketManager = new BucketManager(me, cfg);
			// bucketManager.fetch("外源图片地址", "要上传的七牛目标资源文件夹", "文件名");
			// 这边的文件名如果省略 七牛会随机给个名字
			String picname = Utils.getUUID() + ".jpg";
			FetchRet fetchRet = bucketManager.fetch(url, bucket, picname);
			SKImage im = new SKImage();
			im.setUrl(DOMAIN + fetchRet.key);
			im.setMimeType(fetchRet.mimeType);
			return im;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// 要上传的空间
	private static final String bucketname = "nvzhuang";

	// 密钥
	private static Auth auth = null;

	private static synchronized Auth getAuth() {
		if (auth == null) {
			auth = Auth.create(MyConfigService.getMyConfig("qiniu_accesskey").getVal(), MyConfigService.getMyConfig("qiniu_secretkey").getVal());
		}
		return auth;
	}

	private static final String DOMAIN = "http://file1.janvipiana.com/";

	public static String getUpToken() {
		return getAuth().uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
	}

	// 普通上传
	public String upload(InputStream stream, String name) throws IOException {
		// 创建上传对象
		Configuration cfg = new Configuration(Zone.autoZone());
		UploadManager uploadManager = new UploadManager(cfg);
		try {
			// 调用put方法上传
			String token = getAuth().uploadToken(bucketname);
			if (StringUtils.isEmpty(token)) {
				System.out.println("未获取到token，请重试！");
				return null;
			}
			String houzi = name.substring(name.lastIndexOf("."));

			String key = "bb-" + Utils.getUUID() + houzi;
			Response response = uploadManager.put(stream, key, token, null, null);
			DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			if (response.isOK()) {
				return DOMAIN + putRet.key;
			}
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.toString());
			try {
				// 响应的文本信息
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
		}
		return null;
	}

	// 富文本编辑器的图片转发到七牛
	public static String zhuanfa(String jsonStr) {
		JSONObject json = JSONObject.parseObject(jsonStr);
		String url = json.getString("url");
		String title = json.getString("title");
		String path = Const.ROOT_PATH + url;
		File file = new File(path);
		if (file.exists()) {
			try {
				FileInputStream stream = new FileInputStream(file);
				url = upload1(stream, title);
				stream.close();
				file.delete();
				json.put("url", url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return json.toJSONString();
	}

	// 普通上传
	public static String upload1(InputStream stream, String name) throws IOException {
		// 创建上传对象
		Configuration cfg = new Configuration(Zone.autoZone());
		UploadManager uploadManager = new UploadManager(cfg);
		try {
			// 调用put方法上传
			String token = getAuth().uploadToken(bucketname);
			if (StringUtils.isEmpty(token)) {
				System.out.println("未获取到token，请重试！");
				return null;
			}
			String key = name;
			Response response = uploadManager.put(stream, key, token, null, null);
			DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			if (response.isOK()) {
				return DOMAIN + putRet.key;
			}
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.toString());
			try {
				// 响应的文本信息
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
		}
		return null;
	}

}
